import { Component, OnInit } from "@angular/core";
import { ProductionPlatformService } from "../../proxy/joy/erp/ufida/pmc";
import { DemandOrderDto, KitInput, GetDemandOrderPagedInput } from "../../proxy/joy/erp/ufida/pmc/models";
import * as XLSX from 'xlsx';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'lib-production-platform',
  templateUrl: './production-platform.component.html',
  styleUrls: ['./production-platform.component.less'],
})
export class ProductionPlatformComponent implements OnInit {
  
  dataList: DemandOrderDto[] = [];
  totalCount = 0;
  loading = false;
  analyzing = false;
  exporting = false;
  pageIndex = 1;
  pageSize = 10;
  
  // 齐套分析对话框相关
  isKitAnalysisModalVisible = false;
  selectedAllocationType = '满额分配';
  
  // 齐套状态筛选相关
  kitStatusFilters = {
    allComplete: true,    // 全部齐套
    partialComplete: true, // 部分齐套
    incomplete: true      // 不齐套
  };
  
  constructor(
    private productionPlatformService : ProductionPlatformService,
    private message: NzMessageService
  ){}

  ngOnInit(){
    // 不自动加载数据，等待用户点击"加载订单"按钮
  }

  loadData(forceRefresh: boolean = false) {
    this.loading = true;
    
    const skipCount = (this.pageIndex - 1) * this.pageSize;
    
    // 构建齐套状态筛选条件
    const excludedKitStatuses: string[] = [];
    if (!this.kitStatusFilters.allComplete) {
      excludedKitStatuses.push('全部齐套');
    }
    if (!this.kitStatusFilters.partialComplete) {
      excludedKitStatuses.push('部分齐套');
    }
    if (!this.kitStatusFilters.incomplete) {
      excludedKitStatuses.push('不齐套');
    }
    
    this.productionPlatformService.getList({
      skipCount: skipCount,
      maxResultCount: this.pageSize,
      forceRefresh: forceRefresh,
      sorting: undefined,
      excludedKitStatuses: excludedKitStatuses
    }).subscribe({
      next: (result) => {
        this.totalCount = result.totalCount || 0;
        this.dataList = result.items || [];
        // 递归初始化所有订单项（包括子项）的expanded属性
        this.dataList.forEach(order => {
          this.initExpandedProperty(order);
        });
        this.loading = false;
        console.log('数据加载完成:', { 
          totalCount: this.totalCount, 
          currentPage: this.pageIndex,
          pageSize: this.pageSize,
          itemsCount: this.dataList.length 
        });
      },
      error: () => {
        this.loading = false;
      }
    });
  }

  onKitAnalysis() {
    // 打开齐套分析对话框
    this.isKitAnalysisModalVisible = true;
  }

  handleKitAnalysisCancel() {
    this.isKitAnalysisModalVisible = false;
  }

  handleKitAnalysisOk() {
    this.analyzing = true;
    this.isKitAnalysisModalVisible = false;
    
    const input: KitInput = {
      allocationType: this.selectedAllocationType
    };
    
    this.productionPlatformService.kitAnalysis(input).subscribe({
      next: (result) => {
        // 齐套分析完成后重新加载当前页数据
        this.analyzing = false;
        console.log('齐套分析完成，分配类型：' + this.selectedAllocationType);
        // 重新加载数据以获取最新的齐套信息
        this.loadData(false);
      },
      error: () => {
        this.analyzing = false;
      }
    });
  }

  expandBom(order: any) {
    // 确保expanded属性存在
    if (order.expanded === undefined) {
      order.expanded = false;
    }
    order.expanded = !order.expanded;
  }

  /**
   * 递归初始化树状结构中所有节点的expanded属性
   */
  initExpandedProperty(item: any) {
    if (item.expanded === undefined) {
      item.expanded = false;
    }
    if (item.children && item.children.length > 0) {
      item.children.forEach((child: any) => {
        this.initExpandedProperty(child);
      });
    }
  }

  trackByItem(index: number, item: any): any {
    return `${item.docNo || ''}_${item.docType || ''}_${item.itemMasterId || ''}`;
  }

  getGlobalIndex(index: number): number {
    return (this.pageIndex - 1) * this.pageSize + index + 1;
  }

  onPageIndexChange(pageIndex: number): void {
    this.pageIndex = pageIndex;
    this.loadData(false);
  }

  onPageSizeChange(pageSize: number): void {
    this.pageSize = pageSize;
    this.pageIndex = 1; // 重置到第一页
    this.loadData(false);
  }

  onKitStatusFilterChange(): void {
    // 筛选条件变化时，重置到第一页并重新加载数据
    this.pageIndex = 1;
    this.loadData(false);
  }

  /**
   * 根据齐套状态返回对应的CSS类名
   */
  getKitStatusClass(kitStatus: string): string {
    if (!kitStatus) {
      return '';
    }
    
    const status = kitStatus.trim();
    switch (status) {
      case '全部齐套':
        return 'kit-status-complete';
      case '部分齐套':
        return 'kit-status-partial';
      case '不齐套':
        return 'kit-status-incomplete';
      default:
        return '';
    }
  }

  // 导出Excel
  onExport() {
    if (this.dataList.length === 0) {
      this.message.warning('没有数据可导出，请先加载订单');
      return;
    }

    this.exporting = true;

    // 构建齐套状态筛选条件（与当前筛选保持一致）
    const excludedKitStatuses: string[] = [];
    if (!this.kitStatusFilters.allComplete) {
      excludedKitStatuses.push('全部齐套');
    }
    if (!this.kitStatusFilters.partialComplete) {
      excludedKitStatuses.push('部分齐套');
    }
    if (!this.kitStatusFilters.incomplete) {
      excludedKitStatuses.push('不齐套');
    }

    // 获取所有数据（设置一个很大的maxResultCount）
    const input: GetDemandOrderPagedInput = {
      skipCount: 0,
      maxResultCount: 999999, // 获取所有数据
      forceRefresh: false,
      sorting: undefined,
      excludedKitStatuses: excludedKitStatuses
    };

    this.productionPlatformService.getList(input).subscribe({
      next: (result) => {
        const allData = result.items || [];
        
        if (allData.length === 0) {
          this.message.warning('没有数据可导出');
          this.exporting = false;
          return;
        }

        // 递归展平树形数据
        const flatData: any[] = [];
        let globalIndex = 1;

        const flattenTree = (items: DemandOrderDto[], parentPath: string = '', level: number = 0) => {
          items.forEach((item, index) => {
            const currentPath = parentPath ? `${parentPath}.${index + 1}` : `${index + 1}`;
            
            const row: any = {
              '序号': currentPath,
              '层级': level,
              '物料编码': item.itemCode || '',
              '物料名称': item.itemName || '',
              '物料规格': item.itemSpec || '',
              '单据编号': item.docNo || '',
              '单据类型': item.docType || '',
              '番号': item.seiban || '',
              '需求分类': item.demandCode || '',
              '开工日期': item.startDate ? new Date(item.startDate).toISOString().split('T')[0] : '',
              '调整后开工日期': item.adjustedStartDate ? new Date(item.adjustedStartDate).toISOString().split('T')[0] : '',
              '数量': item.quantity || 0,
              '调整后数量': item.adjustedQuantity || 0,
              '已发数量': item.issuedQuantity || 0,
              '齐套数量': item.kitCount || 0,
              '齐套状态': item.kitStatus || '',
              '产品料号': item.productItemCode || '',
              '产品名称': item.productItemName || '',
              '产品规格': item.productItemSpec || '',
              '产品数量': item.productQuantity || 0,
              '已完成数量': item.complatedQuantity || 0,
              '备注': item.memo || ''
            };

            flatData.push(row);
            globalIndex++;

            // 递归处理子项
            if (item.children && item.children.length > 0) {
              flattenTree(item.children, currentPath, level + 1);
            }
          });
        };

        flattenTree(allData);

        // 创建工作表
        const worksheet = XLSX.utils.json_to_sheet(flatData);
        const workbook = XLSX.utils.book_new();
        
        // 设置列宽
        const colWidths = [
          { wch: 12 },  // 序号
          { wch: 8 },   // 层级
          { wch: 15 },  // 物料编码
          { wch: 30 },  // 物料名称
          { wch: 30 },  // 物料规格
          { wch: 20 },  // 单据编号
          { wch: 12 },  // 单据类型
          { wch: 12 },  // 番号
          { wch: 12 },  // 需求分类
          { wch: 12 },  // 开工日期
          { wch: 15 },  // 调整后开工日期
          { wch: 10 },  // 数量
          { wch: 12 },  // 调整后数量
          { wch: 10 },  // 已发数量
          { wch: 10 },  // 齐套数量
          { wch: 12 },  // 齐套状态
          { wch: 15 },  // 产品料号
          { wch: 30 },  // 产品名称
          { wch: 30 },  // 产品规格
          { wch: 10 },  // 产品数量
          { wch: 12 },  // 已完成数量
          { wch: 30 }   // 备注
        ];
        worksheet['!cols'] = colWidths;

        XLSX.utils.book_append_sheet(workbook, worksheet, '生管平台数据');

        // 生成文件名
        const dateStr = new Date().toISOString().split('T')[0];
        const fileName = `生管平台数据_${dateStr}.xlsx`;

        // 下载文件
        XLSX.writeFile(workbook, fileName);
        
        this.message.success(`成功导出 ${flatData.length} 条数据`);
        this.exporting = false;
      },
      error: (error) => {
        this.message.error('导出失败，请稍后重试');
        this.exporting = false;
      }
    });
  }
}